

// import { _login } from "../../api";
import { useNavigate } from "react-router-dom";
import { useSelector , useDispatch } from "react-redux";
import { InitState , AppDispatch } from "../../utils/types";
import { Dispatch } from "redux";
import { change_user , login_action} from "../../actions";


interface MyReducer {
    loginReducer:InitState
}

const Login = () => {
    const navigate = useNavigate();
    const dispatch:AppDispatch = useDispatch();
    let { username , pwd } = useSelector(({ loginReducer }:MyReducer) => {
        return {
            ...loginReducer
        }
    })
    const subm = async () => {
        if(username !== "" && pwd !== ""){
            const telReg = /^1[3-9]\d{9}$/g;
            if(telReg.test(username)){
                dispatch(login_action({
                    username,
                    pwd
                }));
                navigate("/home");
            }else{
                alert("用户名格式错误，必须是手机号")
            }
        }else{
            alert("用户名/密码不能为空")
        }
        // const { data } = await _login({
        //     username:"温桐",
        //     pwd:"123"
        // });
        // alert(data.msg);
        // if(data.code){
        //     localStorage.setItem("routes",JSON.stringify(data.routes));
        //     navigate("/home");
        // }
    }
    const changeItem = (e:any , key:string) => {
        //  更改store中的state 只能通过派发action 在reducer中更改
        dispatch(change_user(key,e.target.value));
    }
    return (
        <div>
            用户名:<input type="text" value={username} onChange={(e) => changeItem(e,"username")}/>
            密码:<input type="text" value={pwd} onChange={(e) => changeItem(e,"pwd")}/>
            <button onClick={() => subm()}>
                登陆
            </button>
        </div>
    )
};


export default Login;